<template>
  <div
      class="page-scroll"
      ref="scrollEl"
  >
    <slot/>
  </div>
</template>

<script>
import {ref, onActivated, onDeactivated, onBeforeUnmount, nextTick} from 'vue'
import {useRoute} from 'vue-router'

export default {
  name: 'ScrollWrapper',
  setup() {
    const scrollEl = ref(null)
    const isReady = ref(false)
    const route = useRoute()
    const key = `scroll_${route.fullPath}`

    const saveScroll = () => {
      if (scrollEl.value) {
        sessionStorage.setItem(key, scrollEl.value.scrollTop || 0)
      }
    }

    const restoreScroll = () => {
      const y = parseInt(sessionStorage.getItem(key)) || 0
      requestAnimationFrame(() => {
        if (scrollEl.value) {
          scrollEl.value.scrollTop = y
          isReady.value = true // 恢复显示
        }
      })
    }

    onActivated(() => {
      isReady.value = false // 激活时先隐藏
      nextTick(() => {
        // 再等待一帧确保 DOM 高度准备好
        requestAnimationFrame(() => {
          restoreScroll()
          scrollEl.value?.addEventListener('scroll', saveScroll)
        })
      })
    })

    onDeactivated(() => {
      scrollEl.value?.removeEventListener('scroll', saveScroll)
    })

    onBeforeUnmount(() => {
      sessionStorage.removeItem(key)
      scrollEl.value?.removeEventListener('scroll', saveScroll)
    })

    return {
      scrollEl,
      isReady
    }
  }
}
</script>

<style scoped>
.page-scroll {
  /* height: 100%;
  overflow-y: auto; */
}
</style>
